//
//  ProductReducer.m
//  TestOCRedux
//
//  Created by Hotacool on 2019/2/25.
//  Copyright © 2019 Hotacool. All rights reserved.
//

#import "ProductReducer.h"
#import "AppActions.h"
#import "Product.h"

id<HStateType> operateProduct(id<HActionType> action, id<HStateType> state) {
    Product *p = state;
    if ([action.type isEqualToString:kEatAction]) {
        NSInteger add = [action.payload integerValue];
        NSInteger tmp = p.consume + add;
        if (tmp <= p.count) {
            p.consume = tmp;
        }
    } else if ([action.type isEqualToString:kAddAction]) {
        NSInteger add = [action.payload integerValue];
        p.count = p.count + add;
    } else if ([action.type isEqualToString:kAutoAddAction]) {
        NSInteger add = [action.payload integerValue];
        p.count = p.count + add;
    }
    return p;
}

HReducer productReducer(void) {
    HReducer reducer = ^id<HStateType>(id<HActionType> action, id<HStateType> state){
        Product *p = [((Product*)state) copy];
        if ([action.type isEqualToString:kInitialAction]) {
            p = action.payload;
        } else if ([action.type isEqualToString:kJumpToAction]) {
            NSData *data = (NSData*)action.payload;
            NSKeyedUnarchiver *keyedDecoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
            Product *op = [[Product alloc] initWithCoder:keyedDecoder];
            p = op;
        } else {
            p = operateProduct(action, p);
        }
        return p;
    };
    return reducer;
}


